package com.funtonow.jqdk.utils;

import android.content.Context;
import android.hardware.Camera;
import android.os.Build;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String工具类
 *
 */
public class StringUtil {

	static String TAG = "StringUtil";
	//姓名 2-12个字的姓名格式 (?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%\^&*?]+$
	//中文和英文不能同时出现 首尾不能有空格
	public static String sRealName = "^[\u4e00-\u9fa5a-zA-Z0-9·_\\s]{2,20}$";
	public static String sInviteCode = "^[0-9a-zA-Z]+";
	//密码
//	public static String sPassword = "^[0-9a-zA-Z@#%*&$';<>+-.,_]{6,20}$";
//	public static String sPassword= "^(?![a-zA-Z]+$)(?![0-9@#%*&$';<>+-.,_]+$).{6,20}$";
	public static String sPassword = "^[0-9a-zA-Z!$#%\\-~@^&()_*]{6,20}$";
	//座机
	public static String TelFormat = "^[0-9-]{7,20}$";
	//邮箱 w+表示@之前至少要输入一个匹配字母或数字或下划线、点、中横线
	public static String sEmail = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";


	/**
	 * 验证是否是正确的邮箱格式
	 *
	 * @param email
	 * @return true表示是正确的邮箱格式, false表示不是正确邮箱格式
	 */
	public static boolean isEmail(String email) {

		Pattern pattern = Pattern.compile(sEmail);
		boolean flag = false;
		if (email != null) {
			Matcher matcher = pattern.matcher(email);
			flag = matcher.matches();
		}
		return flag;
	}

	/**
	 * 验证密码是否合适
	 *
	 * @param password
	 * @return
	 */
	public static boolean checkPassword(String password) {
		Pattern pattern = Pattern.compile(sPassword);
		Matcher matcher = pattern.matcher(password);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 是否为手机号
	 *
	 * @param phone
	 * @return
	 */
	public static boolean isPhone(String phone) {
		if (phone != null && phone.trim().length() == 11 && phone.startsWith("1")) {
			return true;
		}
		return false;
	}

	/**
	 * 验证是否是 2-12个字的姓名格式
	 *
	 * @param realName
	 * @return
	 */
	public static boolean isRealName(String realName) {
		Pattern pattern = Pattern.compile(sRealName);
		boolean flag = false;
		if (!StringUtil.isEmpty(realName)) {
			Matcher matcher = pattern.matcher(realName.trim());
			flag = matcher.matches();
		}
		return flag;
	}
	
	/**
	 * 验证是否是16位邀请码
	 *
	 * @param invitecode
	 * @return
	 */
	public static boolean isInviteCode(String invitecode) {
		Pattern pattern = Pattern.compile(sInviteCode);
		boolean flag = false;
		if (!StringUtil.isEmpty(invitecode)) {
			Matcher matcher = pattern.matcher(invitecode.trim());
			flag = matcher.matches();
		}
		return flag;
	}

	/**
	 * 座机电话校验
	 *
	 * @param tel
	 * @return
	 */
	public static boolean isRightTel(String tel) {
		Pattern pattern = Pattern.compile(TelFormat);
		Matcher matcher = pattern.matcher(tel);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 证件编号校验
	 *
	 * @param pcno
	 * @return
	 */
	public static boolean isPcNO(String pcno) {
		String format = "^[0-9]{5,50}$";
		Pattern pattern = Pattern.compile(format);
		Matcher matcher = pattern.matcher(pcno);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 通过正则表达式判断是否为手机号
	 *
	 * @param phoneString
	 * @return
	 */
	public static boolean isPhoneNumber(String phoneString) {
		String format = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		return isMatch(format, phoneString);
	}

	/**
	 * 加星号过的电话号码
	 *
	 * @param phoneNo
	 */
	public static String dealPhoneNo(String phoneNo) {
		return phoneNo.substring(0, 3) + "****" + phoneNo.substring(7);
	}

	/**
	 * 从string 获取float值
	 *
	 * @param f
	 * @param format
	 * @return
	 */
	public static String getFloat(String f, String format) {
		if (isEmpty(f)) {
			return "";
		}
		float fl = Float.valueOf(f.trim());
		DecimalFormat df2 = new DecimalFormat(format);
		return df2.format(fl);
	}


	/**
	 * 获取string 标准长度，中文1个，英文两个
	 *
	 * @param s
	 * @return
	 */
	public static int getWordCount(String s) {
		int length = 0;
		for (int i = 0; i < s.length(); i++) {
			int ascii = Character.codePointAt(s, i);
			if (ascii >= 0 && ascii <= 255) {
				length++;
			} else {
				length += 2;
			}

		}
		return length;

	}

	/**
	 * 利用正则表达式获取string 标准长度，中文1个，英文两个
	 *
	 * @param s
	 * @return
	 */
	/*基本原理是将字符串中所有的非标准字符（双字节字符）替换成两个标准字符（**，或其他的也可以）。这样就可以直接例用length方法获得字符串的字节长度了*/
	public static int getWordCountRegex(String s) {
		s = s.replaceAll("[^\\x00-\\xff]", "**");
		int length = s.length();
		return length;
	}

	/**
	 * 按特定的编码格式获取长度 (GBK:中文2个，UTF-8：中文3-4个,GBK有可能收录的中文不全)
	 * @param str
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static int getWordCountCode(String str, String code) {
		try {
			return str.getBytes(code).length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return 0;
		}
	}


	/**
	 * 获得中文字符长度
	 *
	 * @param value
	 * @return
	 */
	public static int getChineseLength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		for (int i = 0; i < value.length(); i++) {
			String temp = value.substring(i, i + 1);
			if (temp.matches(chinese)) {
				valueLength += 1;
			}
		}
		return valueLength;
	}

	/**
	 * 判断字符是否被包括在字符数组里
	 *
	 * @param str
	 * @param arry
	 * @param ch
	 * @return
	 */
	public static boolean contiansInArray(String str, String arry, String ch) {
		if (arry != null && arry.length() > 0) {
			String[] idArry = arry.split(ch);
			if (idArry != null && idArry.length > 0) {
				for (int i = 0; i < idArry.length; i++) {
					if (idArry[i].trim().equals(str.trim())) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 数组是否包含元素
	 *
	 * @param arr
	 * @param str
	 * @return
	 */
	public static boolean isArrayContains(String[] arr, String str) {
		if (arr == null || arr.length == 0) {
			return false;
		}
		for (int i = 0; i < arr.length; i++) {
			String curStr = arr[i];
			if (curStr.equals(str)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 先用,分隔，再用_分隔，判断字符是否被包括在分隔后的第一个字符里
	 *
	 * @param str
	 * @param arry
	 * @return
	 */
	public static boolean contiansInArray(String str, String arry) {
		if (arry != null && arry.length() > 0) {
			String[] idArry = arry.split(",");
			if (idArry != null && idArry.length > 0) {
				for (int i = 0; i < idArry.length; i++) {
					String inquiry = idArry[i].split("_")[0];
					if (inquiry.trim().equals(str.trim())) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static HashMap<String, String> getMapInArray(String arry, String ch) {
		HashMap<String, String> map = new HashMap<String, String>();
		if (arry != null && arry.length() > 0) {
			String[] idArry = arry.split(ch);
			if (idArry != null && idArry.length > 0) {
				for (int i = 0; i < idArry.length; i++) {
					map.put(idArry[i], idArry[i]);
				}
			}
		}
		return map;
	}

	/**
	 * 删除字符数组中的字符,并去掉最后一位分隔符
	 *
	 * @param str
	 * @param arry
	 * @param ch
	 * @return
	 */
	public static String deleteStringInArray(String str, String arry, String ch) {
		StringBuffer sbBuffer = new StringBuffer();
		if (arry != null && arry.length() > 0) {
			String[] idArry = arry.split(ch);
			if (idArry != null && idArry.length > 0) {
				for (int i = 0; i < idArry.length; i++) {
					if (!idArry[i].trim().equals(str.trim())) {
						sbBuffer.append(idArry[i] + ",");
					}
				}
			}
		}
		if (sbBuffer.length() > 0) {
			String endChar = String.valueOf(sbBuffer.charAt(sbBuffer.length() - 1));
			if (endChar != null && endChar.equals(ch)) {
				sbBuffer.deleteCharAt(sbBuffer.length() - 1);
			}
		}
		if (sbBuffer.length() > 0) {
			String beginChar = String.valueOf(sbBuffer.charAt(0));
			if (beginChar != null && beginChar.equals(ch)) {
				sbBuffer.deleteCharAt(0);
			}
		}
		return sbBuffer.toString();
	}


	public static boolean isDraw(int price) {//提现金额
		boolean flag = false;
		if (price >= 50 && price <= 50000) {
			flag = true;
		}
		return flag;
	}

	public static boolean isRecharge(int price) {//充值金额
		boolean flag = false;
		if (price > 0 && price <= 99999) {
			flag = true;
		}
		return flag;
	}

	public static boolean isServicePrice(int price) {//服务价格
		boolean flag = false;
		if (price <= 9999) {
			flag = true;
		}
		return flag;
	}

	public static boolean isServiceLimit(int limit) {//服务周期
		boolean flag = false;
		if (limit >= 2 && limit <= 999) {
			flag = true;
		}
		return flag;
	}

	public static boolean isVideoPrice(int video) {//视频定价
		boolean flag = false;
		if (video >= 1 && video <= 9999) {
			flag = true;
		}
		return flag;
	}


	/**
	 * 判断身高
	 *
	 * @param heightStr
	 * @return
	 */
	public static boolean isHeight(String heightStr) {
		try {
			int height = Integer.parseInt(heightStr);
			if (height >= 1 && height <= 300) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 判断体重
	 *
	 * @param weightStr
	 * @return
	 */
	public static boolean isWeight(String weightStr) {
//        String regular = "^[123]\\d{0,2}(\\.\\d*)?$";
//        Pattern pattern = Pattern.compile(regular);
//        boolean flag = false;
//        if (!StringUtil.isEmpty(weightStr)) {
//            Matcher matcher = pattern.matcher(weightStr);
//            flag = matcher.matches();
//        }
//        if (!flag) {
//            return false;
//        }
		try {
			float weight = Float.parseFloat(weightStr);
			if (weight >= 1 && weight <= 300) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 验证是否是emoji表情
	 *
	 * @param nickName
	 * @return
	 */
	public static boolean containEmoji(String nickName) {
		nickName = nickName.replace("\n", "").replace("\r", "");
		String regular = "^[0-9a-zA-Z\u0024-\uFFFF #!]+$";
		Pattern pattern = Pattern.compile(regular);
		boolean flag = false;
		if (!StringUtil.isEmpty(nickName)) {
			Matcher matcher = pattern.matcher(nickName.trim());
			flag = matcher.matches();
		}
		return flag;
	}

	/**
	 * 验证是否是 1-12个字的昵称格式
	 *
	 * @param nickName
	 * @return
	 */
	public static boolean isNickName(String nickName) {
		String regular = "^[0-9a-zA-Z\u4E00-\u9FA5 ]{1,12}$";
		Pattern pattern = Pattern.compile(regular);
		boolean flag = false;
		if (!StringUtil.isEmpty(nickName)) {
			Matcher matcher = pattern.matcher(nickName);
			flag = matcher.matches();
		}
		return flag;
	}

	/**
	 * 验证是否是 1-12个字的卡片名格式
	 *
	 * @param nickName
	 * @return
	 */
	public static boolean isCardName(String nickName) {
		String regular = "^[0-9a-zA-Z\u4E00-\u9FA5]{1,12}$";
		Pattern pattern = Pattern.compile(regular);
		boolean flag = false;
		if (!StringUtil.isEmpty(nickName)) {
			Matcher matcher = pattern.matcher(nickName);
			flag = matcher.matches();
		}
		return flag;
	}

	static int[] codeArray = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
	static Map<Integer, String> checkCodeDic = new HashMap<Integer, String>();

	static {
		checkCodeDic.put(0, "1");
		checkCodeDic.put(1, "0");
		checkCodeDic.put(2, "X");
		checkCodeDic.put(3, "9");
		checkCodeDic.put(4, "8");
		checkCodeDic.put(5, "7");
		checkCodeDic.put(6, "6");
		checkCodeDic.put(7, "5");
		checkCodeDic.put(8, "4");
		checkCodeDic.put(9, "3");
		checkCodeDic.put(10, "2");
	}

	/**
	 * 验证是否是身份证号
	 *
	 * @param idCard
	 * @return
	 */
	public static boolean isIdCard(String idCard) {
		if (isEmpty(idCard) || idCard.length() != 18) {
			return false;
		}
		int sumValue = 0;
		for (int i = 0; i < 17; i++) {
			char ch = idCard.charAt(i);
			if (!Character.isDigit(ch)) {
				return false;
			}
			sumValue += Integer.valueOf("" + ch) * codeArray[i];
		}
		int checkKey = sumValue % 11;
		String checkCode = checkCodeDic.get(checkKey);
		if (idCard.substring(idCard.length() - 1).toUpperCase().equals(checkCode)) {
			return true;
		}
		return false;
	}
	

	/**
	 * 字符类型识别函数
	 *
	 * @param ch 如果不是汉字、字母、数字则返回false
	 */
	public static boolean charDistinguish(char ch) {
		if (Character.getType(ch) == Character.OTHER_LETTER) {// 汉字
			System.out.println("chinese_leter:" + ch);
			return true;
		} else if (Character.isDigit(ch)) {// 数字
			System.out.println("digit:" + ch);
			return true;
		} else if (Character.isLetter(ch)) {// 字母
			System.out.println("letter:" + ch);
			return true;
		} else {// 其它字符
			System.out.println("others:" + ch);
			return false;
		}
	}

	/**
	 * 判断是中文
	 *
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断输入值是否为空值，如null或者空格
	 *
	 * @param obj 要判断的对象
	 * @return true/false,如为空则返回true
	 */
	public static boolean isBlank(Object obj) {
		return obj == null || obj.toString().trim().length() == 0;
	}

	public static void setTextHight(Context con, TextView tv, int resid, int begin, int end) {
		Spannable span = (Spannable) tv.getText();
		span.setSpan(new ForegroundColorSpan(con.getResources().getColor(resid)), begin, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}


	public static String getStringRemoveHtml(String text) {
		return text.replace("<br/>", "").replace("<br />", "").replace("<p>", "").replace("</p>", "");
	}

	/**
	 * 增加空白
	 */
	public static String addBlank(int size) {
		return String.format("%" + size + "s", "");
	}

	/**
	 * 判断字符串是否为null或者""
	 */
	public static boolean isEmptyOrNull(String content) {
		if (content == null || content.equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 判断字符串是否为IP地址
	 */
	public static boolean isIPAddress(String ipString) {
		if (ipString != null) {
			String[] singleArray = ipString.split("\\.");
			if (singleArray == null) {
				return false;
			}
			for (String numString : singleArray) {
				if (isEmptyOrNull(numString.trim())) {
					return false;
				}
				try {
					int num = Integer.parseInt(numString.trim());
					if (num < 0 || num > 255) {
						return false;
					}
				} catch (NumberFormatException e) {
					return false;
				}

			}
			return true;
		}
		return false;
	}

	/**
	 * 是否是email地址
	 */
	public static boolean isEmailAddress(String emailString) {
		String format = "\\p{Alpha}\\w{2,15}[@][a-z0-9]{3,}[.]\\p{Lower}{2,}";
		return isMatch(format, emailString);
	}

	/**
	 * 是否为数字
	 */
	public static boolean isNumber(String digitString) {
		if (!isEmptyOrNull(digitString)) {
			String regex = "[0-9]*";
			return isMatch(regex, digitString);
		}
		return false;
	}


	/**
	 * 是否为URL地址
	 */
	public static boolean isUrl(String strIp) {
		String strPattern = "^((https?)|(ftp))://(?:(\\s+?)(?::(\\s+?))?@)?([a-zA-Z0-9\\-.]+)"
				+ "(?::(\\d+))?((?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?$";
		return isMatch(strPattern, strIp);
	}

	/**
	 * String 转换成Unicode
	 *
	 * @param string 传入汉字
	 * @return
	 */
	public static String string2Unicode(String string) {
		if (!isEmptyOrNull(string)) {
			char[] charArray = string.toCharArray();
			StringBuffer buffer = new StringBuffer();
			for (char ch : charArray) {
				int code = (int) ch;
				buffer.append(code);
			}
			return buffer.toString();
		}
		return null;
	}

	/**
	 * Unicode转换成String
	 *
	 * @param string
	 * @return
	 */
	public static String unicode2String(String string) {
		if (!isEmptyOrNull(string)) {
			int end = 0;
			String noSpace = string.trim();
			int count = noSpace.length() / 5;
			StringBuffer buffer = new StringBuffer();

			for (int j = 0; j < count; j++) {
				end += 5;
				int uCode = Integer.valueOf(noSpace.substring(j * 5, end));
				buffer.append((char) uCode);

			}
			return buffer.toString();
		}
		return null;
	}


	/**
	 * 获取url参数
	 */
	public static String getParamValueOfUrl(String url, String paramName) {
		try {
			String urls[] = url.split("[?]");
			if (urls.length > 1) {
				String param = urls[1];
				String params[] = param.split("[&]");
				for (String string : params) {
					String keyAndValue[] = string.split("[=]");
					if (keyAndValue.length > 1) {
						String key = keyAndValue[0];
						String value = keyAndValue[1];
						if (key.equalsIgnoreCase(paramName)) {
							return value;
						}
					}
				}
			}
		} catch (Exception e) {
			return "";
		}
		return "";
	}

	/**
	 * 半角转换为全角
	 *
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375) {
				c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 去除特殊字符或将所有中文标号替换为英文标号
	 *
	 * @param str
	 * @return
	 */
	public static String stringFilter(String str) {
		str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("！", "!").replaceAll("：", ":");// 替换中文标号
		String regEx = "[『』]"; // 清除掉特殊字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	/**
	 * 是否为空
	 *
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		if (s == null || s.trim().length() <= 0 || "null".equals(s)) {
			return true;
		}
		return false;
	}

	/**
	 * 字符串正则校验
	 */
	public static boolean isMatch(String regex, String string) {

		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(string);
		return matcher.matches();
	}

	/**
	 * 完整的判断中文汉字和符号
	 *
	 * @param strName
	 * @return
	 */

	public static boolean isChinese(String strName) {

		char[] ch = strName.toCharArray();

		for (int i = 0; i < ch.length; i++) {

			char c = ch[i];

			if (isChinese(c)) {

				return true;

			}

		}

		return false;

	}

	private static boolean checkCameraFacing(final int facing) {
		if (getSdkVersion() < Build.VERSION_CODES.GINGERBREAD) {
			return false;
		}
		final int cameraCount = Camera.getNumberOfCameras();
		Camera.CameraInfo info = new Camera.CameraInfo();
		for (int i = 0; i < cameraCount; i++) {
			Camera.getCameraInfo(i, info);
			if (facing == info.facing) {
				return true;
			}
		}
		return false;
	}
	public static boolean hasBackFacingCamera() {
		final int CAMERA_FACING_BACK = 0;
		return checkCameraFacing(CAMERA_FACING_BACK);
	}
	public static boolean hasFrontFacingCamera() {
		final int CAMERA_FACING_BACK = 1;
		return checkCameraFacing(CAMERA_FACING_BACK);
	}
	public static int getSdkVersion() {
		return Build.VERSION.SDK_INT;
	}


	/**
	 * 验证输入的身份证号是否合法
	 */
	public static boolean isLegalId(String id){
		if (id.toUpperCase().matches("(^\\d{15}$)|(^\\d{17}([0-9]|X)$)")){
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 验证银行卡号
	 * @param cardId
	 * @return
	 */
	public static boolean checkBankCard(String cardId) {
		char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
		if (bit == 'N') {
			return false;
		}
		return cardId.charAt(cardId.length() - 1) == bit;
	}

	/**
	 * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
	 * @param nonCheckCodeCardId
	 * @return
	 */
	private static char getBankCardCheckCode(String nonCheckCodeCardId) {
		if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
				|| !nonCheckCodeCardId.matches("\\d+")) {
			//如果传的不是数据返回N
			return 'N';
		}
		char[] chs = nonCheckCodeCardId.trim().toCharArray();
		int luhmSum = 0;
		for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if (j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
	}

}
